/**
 * Copyright (c) 2017-2022 Rushang Co.Ltd All Rights Reserved.
 */
package com.rshang.rsdp.service.impl;

import com.rshang.rsdp.common.status.ExcelStatusCode;
import com.rshang.rsdp.kit.StrKits;
import com.rshang.rsdp.service.IExcelService;
import com.rshang.rsdp.util.excel.CellKey;
import com.rshang.rsdp.util.i18n.I18nMessage;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 功能简介：<br/>
 *
 * @author zhangjun
 * @create 2017年8月29日下午4:03:38
 */
@Service
public class ExcelServiceImpl implements IExcelService {

    private static final Logger logger = LoggerFactory.getLogger(ExcelServiceImpl.class);

    @Autowired
    I18nMessage i18n;

    private static final String DATE_PATTERN = "yyyy-MM-dd";
    private static final Pattern NUMBER_PATTERN = Pattern.compile("^[0-9]{1,18}(.[0-9]{0,2})?$");

    /* (non-Javadoc)
     * @see com.rshang.rsdp.service.IExcelService#checkCell(int, int, java.lang.String, int, java.util.List, boolean)
     */
    @Override
    public void checkCell(int row, int column, String str, int len, List<String> errList, boolean isRequired) {
        if (isRequired && StringUtils.isEmpty(str)) {
            errList.add(i18n.getMessage(ExcelStatusCode.XLS_STREMPTY.getKey(), new Object[]{row, column + 1}));
        }
        if (!StringUtils.isEmpty(str) && len > 0 && StrKits.length(str) > len) {
            errList.add(i18n.getMessage(ExcelStatusCode.XLS_STRLEN.getKey(), new Object[]{row, column + 1, len}));
        }
    }

    /* (non-Javadoc)
     * @see com.rshang.rsdp.service.IExcelService#checkCell(int, int, java.lang.String, int, java.util.List)
     */
    @Override
    public void checkCell(int row, int column, String str, int len, List<String> errList) {
        checkCell(row, column, str, len, errList, true);
    }

    @Override
    public void checkDateCell(int row, int column, String str, String pattern, List<String> errList,
                              boolean isRequired) {
        if (isRequired && StringUtils.isEmpty(str.trim())) {
            errList.add(i18n.getMessage(ExcelStatusCode.XLS_STREMPTY.getKey(), new Object[]{row, column + 1}));
        }
        if (!StringUtils.isEmpty(str.trim())) {
            //logger.error("checkDateCell str:{} pattern:{}",str,pattern);
            try {
                DateTime.parse(str.trim(), DateTimeFormat.forPattern(pattern)).toString(pattern);
            } catch (Exception e) {
                errList.add(i18n.getMessage(ExcelStatusCode.XLS_DATEFORMATED.getKey(), new Object[]{row, column + 1, pattern}));
            }
        }

    }

    @Override
    public boolean isCellNotEmpty(Cell cell) {
        return cell != null && !StringUtils.isEmpty(cell.getStringCellValue().trim());
    }

    @Override
    public void checkCellValue(int rowNo, int columnNo, CellKey cellKey, Cell cell, List<String> errList) {
        if (cellKey.isRequired() && (cell == null || StringUtils.isEmpty(cell.getStringCellValue().trim())))//是否必填
        {
            errList.add(i18n.getMessage(ExcelStatusCode.XLS_STREMPTY.getKey(), new Object[]{rowNo+"", columnNo + 1, cellKey.getHead()}));
        } else {
            if ("1".equals(cellKey.getType()))//字符型
            {
                //字符串不为空 长度不为0 判断长度是否大于len
                if (cellKey.getLen() > 0 && cell != null && StringUtils.isNotEmpty(cell.getStringCellValue().trim()) && cell.getStringCellValue().trim().length() > cellKey.getLen()) {
                    errList.add(i18n.getMessage(ExcelStatusCode.XLS_STRLEN.getKey(), new Object[]{rowNo+"", columnNo + 1, cellKey.getLen(), cellKey.getHead()}));
                }
            }
            if ("2".equals(cellKey.getType()))//数字型
            {
                if (cell != null && StringUtils.isNotEmpty(cell.getStringCellValue().trim())) {
                    Matcher matcher = NUMBER_PATTERN.matcher(cell.getStringCellValue().trim());
                    //System.out.println("NUMBER_PATTERN:" + cell.getStringCellValue() + "-" + matcher.matches());
                    if (!matcher.matches()) {//数值格式错误
                        errList.add(i18n.getMessage(ExcelStatusCode.XLS_NUMBERERROR.getKey(), new Object[]{rowNo+"", columnNo + 1, cellKey.getHead()}));
                    }
                }
            }
            if ("3".equals(cellKey.getType()))//日期型
            {
                if (cell != null && StringUtils.isNotEmpty(cell.getStringCellValue().trim())) {
                    try {
                        DateTime.parse(cell.getStringCellValue().trim(), DateTimeFormat.forPattern(DATE_PATTERN)).toString(DATE_PATTERN);
                    } catch (Exception e) {
                        errList.add(i18n.getMessage(ExcelStatusCode.XLS_DATEFORMATED.getKey(), new Object[]{rowNo+"", columnNo + 1, DATE_PATTERN, cellKey.getHead()}));
                    }
                }
            }

        }
    }

    @Override
    public void setStringCell(Cell cell) {
        if (cell != null) {
            cell.setCellType(CellType.STRING);
        }
    }

    @Override
    public String getCellValue(Cell cell) {
        return getCellValue(cell, "");
    }

    @Override
    public String getCellValue(Cell cell, String defaultValue) {
        if (cell == null || cell.getStringCellValue().trim().length() == 0) {
            return defaultValue;
        }
        return cell.getStringCellValue().trim();
    }

    @Override
    public Date getDateCellValue(Cell cell) {
        if (cell == null || cell.getStringCellValue().trim().length() == 0) {
            return null;
        }
        return new DateTime(cell.getStringCellValue().trim()).toDate();
    }

}
